<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="其实，要想说清楚类型转换并不是一件容易的事，类型转换可能会发生在每一个代码中，有时候是无知觉的，总的来说C++的类型转换分为隐式类型转换和显示类型转换。">
<meta property="og:type" content="article">
<meta property="og:title" content="C++之类型转换详解">
<meta property="og:url" content="http://luqilinok.github.io/2019/07/07/cpluscplustypeswitch/index.html">
<meta property="og:site_name" content="Lu QiLin&#39;s Blog">
<meta property="og:description" content="其实，要想说清楚类型转换并不是一件容易的事，类型转换可能会发生在每一个代码中，有时候是无知觉的，总的来说C++的类型转换分为隐式类型转换和显示类型转换。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://luqilinok.github.io/2019/07/07/cpluscplustypeswitch/typeswitch.png">
<meta property="og:updated_time" content="2019-07-07T06:18:50.301Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="C++之类型转换详解">
<meta name="twitter:description" content="其实，要想说清楚类型转换并不是一件容易的事，类型转换可能会发生在每一个代码中，有时候是无知觉的，总的来说C++的类型转换分为隐式类型转换和显示类型转换。">
<meta name="twitter:image" content="http://luqilinok.github.io/2019/07/07/cpluscplustypeswitch/typeswitch.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://luqilinok.github.io/2019/07/07/cpluscplustypeswitch/">





  <title>C++之类型转换详解 | Lu QiLin's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Lu QiLin's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-technology">
          <a href="/categories/Technology/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Technology
          </a>
        </li>
      
        
        <li class="menu-item menu-item-notes">
          <a href="/categories/Notes/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Notes
          </a>
        </li>
      
        
        <li class="menu-item menu-item-personal">
          <a href="/categories/Personal/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Personal
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            About
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://luqilinok.github.io/2019/07/07/cpluscplustypeswitch/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LuQiLin">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Lu QiLin's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">C++之类型转换详解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-07T13:41:11+08:00">
                2019-07-07
              </time>
            

            

            
          </span>
          
  <span class="post-updated">
    &nbsp; | &nbsp; 更新于
    <time itemprop="dateUpdated" datetime="2019-07-07T14:18:50+08:00" content="2019-07-07">
      2019-07-07
    </time>
  </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Notes/" itemprop="url" rel="index">
                    <span itemprop="name">Notes</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>其实，要想说清楚类型转换并不是一件容易的事，类型转换可能会发生在每一个代码中，有时候是无知觉的，总的来说C++的类型转换分为隐式类型转换和显示类型转换。</p>
<a id="more"></a>
<hr>
<h1 id="C数据类型转换"><a href="#C数据类型转换" class="headerlink" title="C数据类型转换"></a>C数据类型转换</h1><h2 id="隐式类型转换"><a href="#隐式类型转换" class="headerlink" title="隐式类型转换"></a>隐式类型转换</h2><p>隐式类型转化是编译器默默地、隐式地、偷偷地进行的类型转换，这种转换不需要程序员干预，会自动发生。</p>
<h3 id="赋值转换"><a href="#赋值转换" class="headerlink" title="赋值转换"></a>赋值转换</h3><p>将一种类型的数据赋值给另外一种类型的变量时会发生隐式类型转换，例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">float f = 100;</span><br></pre></td></tr></table></figure>
<p>100是int类型的数据，需要先转换为float类型才能赋值给变量f，再如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">int f = 100.1;</span><br><span class="line">int n = f;</span><br></pre></td></tr></table></figure>
<p>f是float类型的变量，需要先转换为int类型才能赋值给变量n。<br>在赋值运算中，赋值号两边的数据类型不同时，需要把右边表达式的类型转换为左边变量的类型，这可能会导致数据失真，或者精度降低；所以说，隐式类型转换并不一定是安全的。对于不安全的类型转换，编译器一般会给出警告，实验中发现GCC编译器并没有给出任何警告。</p>
<h3 id="运算类型转换"><a href="#运算类型转换" class="headerlink" title="运算类型转换"></a>运算类型转换</h3><p>C语言规定,不同类型的数据需要转换成同一类型后才可进行计算,在整型、实型和字符型数据之间通过类型转换便可以进行混合运算(但不是所有类型之间都可以进行转换) ，转换的规则如下：</p>
<ul>
<li>转换按数据长度增加的方向进行，以保证数值不失真，或者精度不降低。例如，int 和 long 参与运算时，先把 int 类型的数据转成 long 类型后再进行运算；</li>
<li>所有的浮点运算都是以双精度进行的，即使运算中只有 float 类型，也要先转换为 double 类型，才能进行运算；</li>
<li>char 和 short 参与运算时，必须先转换成 int 类型。</li>
</ul>
<p><img src="/2019/07/07/cpluscplustypeswitch/typeswitch.png" alt></p>
<hr>
<h2 id="强制类型转换"><a href="#强制类型转换" class="headerlink" title="强制类型转换"></a>强制类型转换</h2><p>自动类型转换是编译器默默地、隐式地进行的一种类型转换，不需要在代码中体现出来；强制类型转换是程序员明确提出的、需要通过特定格式的代码来指明的一种类型转换。换句话说，自动类型转换不需要程序员干预，强制类型转换必须有程序员干预。<br>强制类型转换的格式为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(type_name) expression</span><br></pre></td></tr></table></figure>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line"></span><br><span class="line">int main() &#123;</span><br><span class="line">        int sum = 100;</span><br><span class="line">        int count = 9;</span><br><span class="line">        double average;</span><br><span class="line">        average = (double)sum / count;</span><br><span class="line">        printf(&quot;average is %lf\n&quot;, average);</span><br><span class="line">        return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">average is 11.111111</span><br></pre></td></tr></table></figure>
<p>注意：对于除法运算，如果除数和被除数都是整形，最后结果也是整形；()的优先级高于/<br>无论是隐式类型转换还是强制类型转换，都只是为了本次运算而进行的临时转换，转换的结果也会保存到临时的内存空间，不会改变数据本来的类型或者值。</p>
<hr>
<h1 id="C-数据类型转换"><a href="#C-数据类型转换" class="headerlink" title="C++数据类型转换"></a>C++数据类型转换</h1><h2 id="隐式类型转换-1"><a href="#隐式类型转换-1" class="headerlink" title="隐式类型转换"></a>隐式类型转换</h2><p>C++包括C的隐式类型转换，除此之外，在C++中，将某种类型的对象拷贝到另一种不同类型的对象中时就会发生隐式转型。比如返回值（函数声明的返回值与代码块实际返回值不同的情况下），按值传递异型参数等情况均会发生隐式类型转换。<br>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">class A &#123;&#125;; </span><br><span class="line">class B</span><br><span class="line">&#123;</span><br><span class="line">    public: B (A a) &#123;&#125;</span><br><span class="line">    public: B (int c, int d = 0);</span><br><span class="line">    public: operator double() const; </span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">A a;</span><br><span class="line">B b1 = a;</span><br><span class="line">B b2 = 10;</span><br><span class="line">B b3;</span><br><span class="line">double d;</span><br><span class="line">d = 10 + b3;</span><br></pre></td></tr></table></figure>
<p>此外C++也不能在转换过程中进行连续的隐式类型转换，例如A可以隐式转换为B，B可以隐式转换为C，但A不能隐式转换为C。<br>可以通过关键字explict可以来规避可被单参调用的构造函数引起的隐式类型转换。上例中，如果声明 explicit B(A a)，b1=a就不会发生隐式类型转换，编译错误。</p>
<hr>
<h2 id="显示类型转换"><a href="#显示类型转换" class="headerlink" title="显示类型转换"></a>显示类型转换</h2><p>C++语言也支持C语言的类型强制类型转换，但这种转换可以在两种不同类型的对象的指针之间进行，这很可能是相当危险的事情。所以 C++ 提供四种转换操作符来细分显式类型转换。</p>
<h3 id="const-cast"><a href="#const-cast" class="headerlink" title="const_cast"></a>const_cast</h3><ul>
<li><p>1、常量指针被转化成非常量的指针，并且仍然指向原来的对象； </p>
</li>
<li><p>2、常量引用被转换成非常量的引用，并且仍然指向原来的对象； </p>
</li>
<li><p>3、const_cast一般用于修改指针。如const char *p形式;</p>
</li>
<li><p>4、const_cast也可以去除对象的valatile属性。</p>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;iostream&gt;</span><br><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">using namespace std;</span><br><span class="line"></span><br><span class="line">int main() &#123;</span><br><span class="line">        int a = 5;</span><br><span class="line">        const int *p = &amp;a;</span><br><span class="line">        // *p = 6; // error</span><br><span class="line">        int *p2 = const_cast&lt;int*&gt;(p);</span><br><span class="line">        *p2 = 6;</span><br><span class="line">        printf(&quot;%d\n&quot;, a);</span><br><span class="line">        return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>注意：对定义为常量的参数，使用const_cast会出现未定义的行为，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">#include&lt;iostream&gt;</span><br><span class="line">using namespace std;</span><br><span class="line">int main() &#123;</span><br><span class="line">    const int c_val = 233;  //声明为常量类型</span><br><span class="line">    int &amp;use_val = const_cast&lt;int&amp;&gt;(c_val); //使用去const 引用</span><br><span class="line">    int *ptr_val = const_cast&lt;int*&gt;(&amp;c_val);//使用去const 指针</span><br><span class="line"></span><br><span class="line">    use_val = 666;  //未定义行为</span><br><span class="line">    cout &lt;&lt; c_val &lt;&lt; &quot;\t&quot; &lt;&lt; use_val &lt;&lt; &quot;\t&quot; &lt;&lt; *ptr_val &lt;&lt; endl;</span><br><span class="line">    *ptr_val = 110; //未定义行为</span><br><span class="line">    cout &lt;&lt; c_val &lt;&lt; &quot;\t&quot; &lt;&lt; use_val &lt;&lt; &quot;\t&quot; &lt;&lt; *ptr_val &lt;&lt; endl;</span><br><span class="line">    return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>gcc下输入：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">233	666	666</span><br><span class="line">233	110	110</span><br></pre></td></tr></table></figure>
<p>c_val、use_val和ptr_val的地址是一样的，但是c_val的值并没有发生改变，这点非常令人匪夷所思。</p>
<h3 id="static-cast"><a href="#static-cast" class="headerlink" title="static_cast"></a>static_cast</h3><ul>
<li><p>1、static_cast 作用和C语言风格强制转换的效果基本一样，由于没有运行时类型检查来保证转换的安全性，所以这类型的强制转换和C语言风格的强制转换都有安全隐患；</p>
</li>
<li><p>2、用于类层次结构中基类（父类）和派生类（子类）之间指针或引用的转换。注意：进行上行转换（把派生类的指针或引用转换成基类表示）是安全的；进行下行转换（把基类指针或引用转换成派生类表示）时，由于没有动态类型检查，所以是不安全的。</p>
</li>
<li><p>3、用于基本数据类型之间的转换，如把int转换成char，把int转换成enum。这种转换的安全性需要开发者来维护。</p>
</li>
<li><p>4、static_cast不能转换掉原有类型的const、volatile、或者 __unaligned属性。(前两种可以使用const_cast 来去除)</p>
</li>
<li><p>5、c++ 的任何的隐式转换都是使用 static_cast 来实现。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">/* 常规的使用方法 */</span><br><span class="line">float f_pi=3.141592f</span><br><span class="line">int   i_pi=static_cast&lt;int&gt;(f_pi); /// i_pi 的值为 3</span><br><span class="line"></span><br><span class="line">/* class 的上下行转换 */</span><br><span class="line">class Base&#123;</span><br><span class="line">    // something</span><br><span class="line">&#125;;</span><br><span class="line">class Sub:public Base&#123;</span><br><span class="line">    // something</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//  上行 Sub -&gt; Base</span><br><span class="line">//编译通过，安全</span><br><span class="line">Sub sub;</span><br><span class="line">Base *base_ptr = static_cast&lt;Base*&gt;(&amp;sub);  </span><br><span class="line"></span><br><span class="line">//  下行 Base -&gt; Sub</span><br><span class="line">//编译通过，不安全</span><br><span class="line">Base base;</span><br><span class="line">Sub *sub_ptr = static_cast&lt;Sub*&gt;(&amp;base);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="dynamic-cast"><a href="#dynamic-cast" class="headerlink" title="dynamic_cast"></a>dynamic_cast</h3><p>dynamic_cast运算符是强制类型转换，应该是这四种中最特殊的一个,因为他涉及到面向对象的多态性和程序运行时的状态,也与编译器的属性设置有关.所以不能完全使用C语言的强制转换替代,它也是最常有用的,最不可缺少的一种强制转换。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;iostream&gt;</span><br><span class="line">using namespace std;</span><br><span class="line"></span><br><span class="line">class Parent &#123;</span><br><span class="line">public:</span><br><span class="line">    void print() &#123;</span><br><span class="line">        cout &lt;&lt; &quot;Parent&quot; &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">    virtual void virFunction() &#123;&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">class Children : public Parent &#123;</span><br><span class="line">public:</span><br><span class="line">    void print() &#123;</span><br><span class="line">        cout &lt;&lt; &quot;Children&quot; &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">    virtual void virFunction() &#123;&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">int main() &#123;</span><br><span class="line">    Children *child = new Children;</span><br><span class="line">    child-&gt;print();</span><br><span class="line">    cout &lt;&lt; &quot;Children -&gt; Parent &quot; &lt;&lt; endl;</span><br><span class="line">    Parent *parent1 = static_cast&lt;Parent*&gt;(child);</span><br><span class="line">    if (parent1 != NULL) parent1-&gt;print();</span><br><span class="line">    Parent *parent2 = (Parent*)child;</span><br><span class="line">    if (parent2 != NULL) parent2-&gt;print();</span><br><span class="line">    Parent *parent3 = dynamic_cast&lt;Parent*&gt;(child);</span><br><span class="line">    if (parent3 != NULL) parent3-&gt;print();</span><br><span class="line"></span><br><span class="line">    Parent *parent = new Parent;</span><br><span class="line">    parent-&gt;print();</span><br><span class="line">    cout &lt;&lt; &quot;Children -&gt; Parent &quot; &lt;&lt; endl;</span><br><span class="line">    Children *child1 = static_cast&lt;Children*&gt;(parent);</span><br><span class="line">    if (child1 != NULL) child1-&gt;print();</span><br><span class="line">    Children *child2 = (Children*)parent;</span><br><span class="line">    if (child2 != NULL) child2-&gt;print();</span><br><span class="line">    Children *child3 = reinterpret_cast&lt;Children*&gt;(parent);</span><br><span class="line">    if (child3 != NULL) child3-&gt;print();</span><br><span class="line">    Children *child4 = dynamic_cast&lt;Children*&gt;(parent);</span><br><span class="line">    if (child4 != NULL) child4-&gt;print();</span><br><span class="line"></span><br><span class="line">    return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Children</span><br><span class="line">Children -&gt; Parent</span><br><span class="line">Parent</span><br><span class="line">Parent</span><br><span class="line">Parent</span><br><span class="line">Parent</span><br><span class="line">Parent -&gt; Children</span><br><span class="line">Children</span><br><span class="line">Children</span><br><span class="line">Children</span><br></pre></td></tr></table></figure>
<ul>
<li>从子类到父类的转换：static_cast和dynamic_cast都可以做到</li>
<li>从父类到子类的转换：static_cast和dynamic_cast也都是成功的，但是static_cast返回了值，而dynamic_cast返回空指针，事实上，父类转换为子类是未定义的结果，而static_cast调用了子类的函数。reinterpret也可以进行类型转换，和static_cast输出是一样的。<br>结论：static_cast和reinterpret_cast运算符要么直接被编译器拒绝进行转换，要么就一定会得到相应的目标类型的值。 而dynamic_cast却会进行判别，确定源指针所指的内容，是否真的合适被目标指针接受。如果是否定的，那么dynamic_cast则会返回null。这是通过检查”运行期类型信息”（Runtime type information，RTTI）来判定的，它还受到编译器的影响，有些编译器需要设置开启才能让程序正确运行。<br>其次，进行dynamic_cast转换时，必须要提供虚函数，如果上例中没有虚函数，就会发生编译错误。</li>
</ul>
<h3 id="reinterpret-cast"><a href="#reinterpret-cast" class="headerlink" title="reinterpret_cast"></a>reinterpret_cast</h3><p>reinterpret_cast运算符是用来处理无关类型之间的转换；它会产生一个新的值，这个值会有与原始参数（expressoin）有完全相同的比特位。<br>IBM的C++指南告诉我们reinterpret_cast可以用在什么地方作为转换运算符：</p>
<ul>
<li><p>从指针类型到一个足够大的整数类型</p>
</li>
<li><p>从整数类型或者枚举类型到指针类型</p>
</li>
<li><p>从一个指向函数的指针到另一个不同类型的指向函数的指针</p>
</li>
<li><p>从一个指向对象的指针到另一个不同类型的指向对象的指针</p>
</li>
<li><p>从一个指向类函数成员的指针到另一个指向不同类型的函数成员的指针</p>
</li>
<li><p>从一个指向类数据成员的指针到另一个指向不同类型的数据成员的指针</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">#include&lt;iostream&gt;</span><br><span class="line">#include&lt;stdint.h&gt;</span><br><span class="line">using namespace std;</span><br><span class="line"></span><br><span class="line">int main() &#123;</span><br><span class="line">    int *ptr = new int(233);</span><br><span class="line">    uint64_t ptr_addr = reinterpret_cast&lt;uint64_t&gt;(ptr);</span><br><span class="line">    cout &lt;&lt; &quot;ptr 的地址: &quot; &lt;&lt; hex &lt;&lt; ptr &lt;&lt; endl</span><br><span class="line">        &lt;&lt; &quot;ptr_addr 的值(hex): &quot; &lt;&lt; hex &lt;&lt; ptr_addr &lt;&lt; endl;</span><br><span class="line">    delete ptr;</span><br><span class="line">    return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>运行结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ptr 的地址: 0x1dc2010</span><br><span class="line">ptr_addr 的值(hex): 1dc2010</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/06/30/cpluscplusstatic/" rel="next" title="C++之静态详解">
                <i class="fa fa-chevron-left"></i> C++之静态详解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/07/cpluscplusmemorypack/" rel="prev" title="C/C++内存对齐策略">
                C/C++内存对齐策略 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">LuQiLin</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#C数据类型转换"><span class="nav-number">1.</span> <span class="nav-text">C数据类型转换</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#隐式类型转换"><span class="nav-number">1.1.</span> <span class="nav-text">隐式类型转换</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#赋值转换"><span class="nav-number">1.1.1.</span> <span class="nav-text">赋值转换</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运算类型转换"><span class="nav-number">1.1.2.</span> <span class="nav-text">运算类型转换</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#强制类型转换"><span class="nav-number">1.2.</span> <span class="nav-text">强制类型转换</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#C-数据类型转换"><span class="nav-number">2.</span> <span class="nav-text">C++数据类型转换</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#隐式类型转换-1"><span class="nav-number">2.1.</span> <span class="nav-text">隐式类型转换</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#显示类型转换"><span class="nav-number">2.2.</span> <span class="nav-text">显示类型转换</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#const-cast"><span class="nav-number">2.2.1.</span> <span class="nav-text">const_cast</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#static-cast"><span class="nav-number">2.2.2.</span> <span class="nav-text">static_cast</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#dynamic-cast"><span class="nav-number">2.2.3.</span> <span class="nav-text">dynamic_cast</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#reinterpret-cast"><span class="nav-number">2.2.4.</span> <span class="nav-text">reinterpret_cast</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LuQiLin</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
